﻿using AutoMapper;
using MediatR;
using S.Organization.API.Application.Command.FieldSettingCommand;
using S.Organization.API.Application.Command.SheepFarmCommand;
using S.Organization.Domian.Model;
using S.Organization.Infrastructure;

namespace S.Organization.API.Application.CommandHandler.FieldSettingCommandHandler
{
    public class AddFieldSettingCommandHandler : IRequestHandler<AddFieldSettingCommand, int>
    {
        private readonly IBaseRepository<FieldSetting> _repository;
        private readonly IMapper mapper;

        public AddFieldSettingCommandHandler(IBaseRepository<FieldSetting> repository, IMapper mapper)
        {
            _repository = repository;
            this.mapper = mapper;
        }

        public async Task<int> Handle(AddFieldSettingCommand request, CancellationToken cancellationToken)
        {

            var fieldsetting = await _repository.GetAllAsync();

            if (request.AddType)
            {
                var count = fieldsetting.Where(x => x.FieldName == request.Name).Count();
                if (count > 0)
                {
                    return -2;
                }
                FieldSetting list=new FieldSetting();
                list.FieldName = request.Name; 
                list.CottageId=request.CottageId;
                return await _repository.CreateAsync(list);

            }
            else
            {
                for (int i=1;i<= request.Count;i++)
                {

                    string name =request.CottageName+request.StartNumber.ToString().PadLeft(5, '0');
                    request.StartNumber++;
                    FieldSetting list = new FieldSetting();
                    list.FieldName = name;
                    var count = fieldsetting.Where(x => x.FieldName == list.FieldName).Count();
                    if (count > 0)
                    {
                        return -2;
                    }
                    list.CottageId = request.CottageId;
                    await  _repository.CreateAsync(list);
                }
                return 1;
            }
        }
    }
}
